package com.example.demo.service.impl;
import com.example.demo.dao.TenantDbConfigRepository;
import com.example.demo.dto.TenantDbConfigDTO;
import com.example.demo.model.TenantDbConfig;
import com.example.demo.service.TenantDbConfigService;
import com.example.demo.tenant.MultiTenantConnectionProvider;
import com.example.demo.tenant.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.sql.SQLException;
import java.util.*;

/**
 * @description: 租户数据源配置 接口实现
 */
@Slf4j
@Service
@Transactional(rollbackOn = SQLException.class)
public class TenantDbConfigServiceImpl implements TenantDbConfigService {

    @Resource
    private TenantDbConfigRepository tenantDbConfigRepository;

    @Autowired
    private MultiTenantConnectionProvider multiTenantConnectionProvider;

    @Override
    public void initDataSource() {
        // 启动项目 加载不同的数据源
        List<TenantDbConfig> configList = tenantDbConfigRepository.findByEnable(1);
        if (CollectionUtils.isEmpty(configList)) {
            throw new RuntimeException("查询不到数据源");
        } else {
            for (TenantDbConfig config : configList) {
                if(TenantContextHolder.dataSourceMap.containsKey(config.getTenantId())) {
                    continue;
                }
                TenantDbConfigDTO configDTO = new TenantDbConfigDTO();
                BeanUtils.copyProperties(config, configDTO);
                multiTenantConnectionProvider.addDataSource(configDTO);
            }
        }
    }
}
